class Parser(object):
	"""Simple parser class for line or file.
	"""
	def __init__(self, rule):
		"""Constructor. Needs a Rule object for parse algorithm.
		"""
		self.setrule(rule)
	
	def setrule(self,rule):
		"""Add the parse-rule. Need to implement parse(string) method that return a list.
		"""
		try:
			rule.parse("0")
			self.rule = rule
		except:
			raise TypeError("Parser > setrule > Rule object must implement parse(string) method")
	
	def parseline(self, line):
		"""Parse single line, return a list.
		"""
		if not line: return []
		values = self.rule.parse(line)
		return values
	def parsefile(self, namefile):
		"""Parse multiline file, return a list that contains a list for each parsed line.
		"""
		lists = []
		datafile = open(namefile)
		for line in datafile:
			lists.append(self.parseline(line))
		return lists

class CSVRule(object):
	"""CSV (Comma Separated Values) for float number.
	Example:
	>> r = CSVRule()
	>> s = "1.2 , 3.4 , 1 , 1.0 "
	>> r.parse(s)
	[1.2, 3.4, 1.0, 1.0]
	"""
	def __init__(self, sep=","):
		self.sep = sep
	
	def parse(self, string):
		try:
			string = str(string)
		except: 
			raise TypeError("CSVRule > parse > Parse method accept string as input. {0} is not a string".format(string))
		strings = string.split(self.sep)
		return [self._parsefloat(s) for s in strings if bool(s)]

	def _parsefloat(self, s):
		try:
			return float(s)
		except:
			raise TypeError("CSVRule > parsefloat > {0} is not a float!".format(s))

# factory
def getCSVParser():
	"""Get Parser for CSV, separator between values is ','
	"""
	p = Parser(CSVRule())
	return p

